package program;

import kernel.FileManager;
import kernel.exception.OSException;
import kernel.process.AbstractProcess;
import kernel.process.AbstractProcessHeader;

/**
 * Ls/Dir process.
 * For more see man() method.
 * @author Petr Hajek, Veronika Vencurikova
 *
 */
public class Ls extends AbstractProcess {
	public static final String LONG = "-l";

	public Ls(AbstractProcessHeader header, long pid) {
		super(header, pid);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String doJob(String input) throws OSException {
		boolean longInf = false;
		if (this.params.size() > 2) throw new OSException(OSException.ERR_MANY_ARGS);
		else if (this.params.size() > 1) {
			if (this.params.get(0).equals(LONG)) {
				longInf = true;
				input = this.params.get(1);
			}
			else if (this.params.get(1).equals(LONG)) {
				longInf = true;
				input = this.params.get(0);
			}
			else throw new OSException(OSException.ERR_MANY_ARGS);
		}
		else if (this.params.size() > 0) {
			if (this.params.get(0).equals(LONG)) {
				longInf = true;
			}
			else {
				longInf = false;
			}
		}
		else {
			longInf = false;
		}
		
		String out = "";
		String[] arr = null;
		if (input.contains("*") || input.contains("?")) {
			arr = FileManager.getDirContentUsingRegex(getWd(shellID), input, longInf);
		}
		else {
			arr = FileManager.getDirContent(absPath(input, shellID), longInf);
		}
		out = "";
		for (int i = 0; i < arr.length; i++) {
			out += arr[i] + "\n";
		}
		return out;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean needParams() {
		return false;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void kill() throws OSException {

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String continueJob() throws OSException {
		this.shouldEnd = true;
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected String finalizeJob() throws OSException {
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String man(String command) {
	String man = "";
			
			man += "    lists directory contents\n";
			man += "\n";
			man += "Command syntax:\n";
			man += "    "+command+" [OPTION][FILE]\n";
			man += "\n";
			man += "Description:\n";
			man += "    -l - lists file name, size, date and time of last modification\n";
			
			return man;
	}

}
